﻿mainModule.controller("columnEditCtrl", ["$scope", "$rootScope", "columnSvc", "notification", "pageState", "$routeParams", "cache", function ($scope, $rootScope, columnSvc, notification, pageState, $routeParams, cache) {
    var mode;
    var articleID = $routeParams.articleID;
    var articleFindByIdUrl = "/api/articleapi/" + articleID;    

    setAddMode();
    $scope.$on('itemClicked', function (e, item) {
        setEditMode(item);
    });

    function setEditMode(item) {
        mode = "edit";
        $scope.item = item;
    }
    function setAddMode() {        
        mode = "add";        
        $scope.item = {};
        $scope.item.ArticleID = articleID;        
    }
       
    $scope.cancel = function () {
        setAddMode();
        $scope.$emit('resetIndex');
    }

    $scope.save = function () {
        var editAddPromise;
        if (mode === "edit")
            editAddPromise = columnSvc.edit($scope.item);
        else 
            editAddPromise = columnSvc.add($scope.item);

        editAddPromise.then(function (response) {
            if (response.data.Success) {
                $scope.$emit('listReload');
            }
            cache.remove(articleFindByIdUrl);
            setAddMode();
            notification.notify(response.data);           
        });        
    }
}])